package ink.lovejinhu.linkedList.solve;

import ink.lovejinhu.common.ListNode;
import ink.lovejinhu.common.ProductList;
import org.junit.Test;

/**
 * @author jinhu
 * created 2021-02-19 15:48
 */
public class LinkedList_0002_ReverseList_MToN {
    /**
     * 逆置链表上m到n这个区间的节点
     *
     * @param head
     * @param M
     * @param N
     * @return
     */
    public ListNode reverseBetween(ListNode head, int M, int N) {
        //目标:找M-1位置的节点和N-1位置的节点
        int length = N - M + 1;
        ListNode resultNode = head;
        ListNode M_Pre = null;
        ListNode M_Node = null;
        ListNode temp_node = null;
        ListNode new_M = null;
        while (M > 2) {
            head = head.next;
            M--;
        }
        /**
         * head处于M-1的位置了
         */
        M_Pre = head;
        head = head.next;
        M_Node = head;
        /**
         * 逆置N-M节点
         */
        while (length > 0) {
            temp_node = head.next;
            head.next = new_M;
            new_M = head;
            head = temp_node;
            length--;
        }
        /**
         * head处于N+1这个结点位置
         */
        M_Node.next = head;
        M_Pre.next = new_M;
        return resultNode;
    }

    @Test
    public void test01() {
        ProductList productList = new ProductList();
        ListNode listNode = productList.creatListByLength(new int[]{1, 2, 3, 4, 5, 6, 7, 8});
        productList.printListNode(listNode);
        ListNode listNode1 = this.reverseBetween(listNode, 1, 6);
        productList.printListNode(listNode1);
    }
}
